const Image = require('../dao/image');
const Animation = require('../dao/animation');
const Banner = require('../dao/banner');
const { OK, ERR } = require('../util/util');
const Formats = require('../util/formats');

module.exports = {
    /**
     * 初始化
     */
    init: function(req, res, next) {
        Banner.init();
        Image.init();
        Animation.init();
        res.json(OK({}));
        return;
    },
    /**
     * 获取所有
     */
    findAll: function(req, res, next) {
        console.log("request params: ", "limit=", req.query.limit || 16, "offset=", req.query.offset || 0);

        const banners = {};
        Banner.findAll()
        .then(function(resData){
          let banners = [];
          resData.forEach(b => {
            banners.push(Formats.Banner(b));
          });
          return banners;
        })
        .then(function (banners) {
          Image.findAll(req.query.limit, req.query.offset)
          .then(function(resData){
            let cs = [];
            resData.forEach(i => {
              cs.push(Formats.Image(i));
            });
            res.json(OK({bannerList: banners,imageData:cs}));
          });
        })

        return;
    },
    /**
     * 获取指定数据
     */
    findById: function(req, res, next) {
      console.log("request params: ", "id=", req.params.id || "");
      Image.findById(req.params.id)
      .then(function(resData){
        return Formats.Image(resData);
      })
      .then(function(response){
        Animation.findByImageId(req.params.id)
        .then(function(resData){
          resData = resData || "";
          console.log("Animation: ", resData);
          response.animation=JSON.parse(resData.context);
          res.json(OK(response));
        })
      });
      return;
    }
}
